import "./game.css"
import GridItem from "./components/GridItem";
import { useEffect, useRef, useState } from "react";

function calculateWinner(arr: any) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const c = arr.filter(function (v: number) {
      return lines[i].indexOf(v) > -1
    });
    if (c.length === 3) {
      return true
    }
  }
  return null;
}

export default function Game() {
  const [list, setList] = useState(Array(9).fill(""))
  const ref = useRef<any>(null)
  const [nextPlayer, setNextPlayer] = useState("x")
  const [winer, setWiner] = useState("")
  const [playerObj, setPlayerObj] = useState<any>({
    x: [],
    o: [],
  })

  const updatePlayer = (value: number) => {
    // 更新对象时，以下是在结果上是正确的，但是没有遵循 不可变原则
    // playerObj[nextPlayer].push(value)
    setPlayerObj((prev: any) => ({
      ...prev,
      [nextPlayer]: [...prev[nextPlayer], value]
    }))
    // console.log(playerObj)
    setList((prev: any) => (
      prev.map((item: any, index: number) => index === value ? nextPlayer : item)
    ))
    // list.splice(value, 1, nextPlayer)
    setNextPlayer(nextPlayer === "x" ? "o" : "x")
  }
  const clear = () => {
    setNextPlayer("x")
    setWiner("")
    setPlayerObj({
      o: [],
      x: []
    })
    setList(Array(9).fill(""))
  }
  // 状态更新后的
  useEffect(() => {
    const xList = playerObj.x
    const oList = playerObj.o
    const xWin = calculateWinner(xList)
    const oWin = calculateWinner(oList)
    if (xWin) {
      setWiner("x")
    }
    if (oWin) {
      setWiner("o")
    }
    if (playerObj["x"].length + playerObj["o"].length === 9) {
      alert("和棋")
    }
  }, [playerObj])
  return (
    <>
      <h2>下一次执行: {nextPlayer}</h2>
      <h2>赢家: {winer}</h2>
      <button onClick={clear}>清空</button>
      <div className="box">

        {
          list.map((a, idx) => <GridItem key={idx}
                                         value={idx}
                                         value2={a}
                                         winer={winer}
                                         ref={ref}
                                         nextPlayer={nextPlayer}
                                         updatePlayer={updatePlayer} />)
        }
      </div>
    </>
  )
}
